﻿#include "HttpRequest.h"

#include "IPAddress.h"
#include "Output/Console.h"

#include "TCPClient.h"

#include "Containers/String8.h"
#include "HttpResponse.h"

void CHttpRequest::ProcessRequest()
{
    TOptional<SIPAddress> HostIP = ParseHostName(Url.GetHost());
    if(!HostIP)
    {
        WH::PrintLine(U"无法解析主机地址");
        return;
    }

    Socket=CTCPClient::Create();
    Socket->Connect(HostIP.GetValue(), Url.GetPort());

    if(!Socket->IsConnected())
    {
        WH::PrintLine(U"无法连接到服务器");
        return;
    }

    Socket->OnDataReceived.Bind([this]()
    {
        TVector<uint8_t> StringData = this->Socket->ReadAllData();
        StringData.Add(u8'\0');
        CString String((char8_t*)StringData.Data());

        auto Response = CHttpResponse::Parse(String);
        if(!Response)
        {
            //parse response failed
            WH::PrintLine(U"解析响应失败");
            WH::PrintLine(String);
            return;
        }

        OnRequestFinished.ExecuteIfBound(Response);
    });

    //make request string
    CString RequestString;
    RequestString += WH::RequestMethodToString(Method);
    RequestString += U" ";
    RequestString += Url.GetPath();
    RequestString += U" ";
    RequestString += HttpVersion;
    RequestString += U"\r\n";

    for(auto &HeadParameter:HeadParameters)
    {
        RequestString += HeadParameter.Key;
        RequestString += U": ";
        RequestString += HeadParameter.Value;
        RequestString += U"\r\n";
    }

    RequestString += U"\r\n";

    if(Method==EHttpRequestMethod::POST)
    {
        RequestString += Body;
    }

    Socket->Send(RequestString);
}

TOptional<SIPAddress> CHttpRequest::ParseHostName(const CString &HostName)
{
    return  SIPAddress::Create(Url.GetHost());
}

